package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.service.WeChatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WeChatServiceImpl implements WeChatService {

    private static final String OPENID_URL="https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    private static final String PHONE_URL="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    private static  final String TOKEN_URL="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    @Value("${wechat.appid}")
    private String appId;

    @Value("${wechat.secret}")
    private String secret;

    /**
     * 获取openid
     *
     * @param code
     * @return
     */
    @Override
    public String getOpenId(String code) {
        Map<String,Object> loginMap = getAppConfig();
        loginMap.put("js_code",code);
        String request = HttpUtil.get(OPENID_URL, loginMap);
        JSONObject jsonObject = JSONUtil.parseObj(request);
        if (jsonObject.getInt("errcode") != null){
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }

        return jsonObject.getStr("openid");
    }

    private Map<String, Object> getAppConfig() {
        Map<String,Object> loginMap = new HashMap<>();
        loginMap.put("appid",appId);
        loginMap.put("secret",secret);
        return loginMap;
    }

    /**
     * 获取手机号
     *
     * @param detailCode
     * @return
     */
    @Override
    public String getPhone(String detailCode) {
        String token = getToken();
        String url= PHONE_URL+token;
        Map<String,Object> phoneMap = new HashMap<>();
        phoneMap.put("code",detailCode);

        JSONObject jsonObject = JSONUtil.parseObj(HttpUtil.post(url, JSONUtil.toJsonStr(phoneMap)));
        if (jsonObject.getInt("errcode")!=0) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
    }

    private String getToken() {
        Map<String,Object> loginMap =getAppConfig();
        String json = HttpUtil.get(TOKEN_URL, loginMap);
        JSONObject jsonObject = JSONUtil.parseObj(json);
        if (ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))){
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getStr("access_token");
    }


}
